from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.shortcuts import render, get_object_or_404
from django.shortcuts import get_list_or_404
from django.http import HttpResponse

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template.defaulttags import csrf_token

from django.template import RequestContext, loader
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.contrib.auth.decorators import login_required
# Create your views here.

from tools import load_template
from tools import current_user
from tools import get_current_c_user
from tools import session_mixs

from user.forms import *
from isa.models import *
from article.models import *
# Create your views here.



@load_template("article/article_box")
def article_box_view(request,tag="all"):
    user = current_user(request)
    cuser = get_current_c_user(request)

    if request.method == "GET":
        # u = get_object_or_404(Articles,id=type_id)
        ars = Articles.get_by_tag(tag)
        for ar in ars :
            ar.abstruct = ar.get_abstruct()
        tags = set([tag.content for tag in  ATags.objects.all()])
        print(tags)
        ars = [ar for ar in ars if set([ t.content for t in  ar.atags_set.all()]).issubset(tags)]
        context = RequestContext(request,{
                'articles':ars,
                'u':cuser,
                'tags':tags,

            })

        return HttpResponse(template.render(context))


@load_template("article/article")
def article_view(request,type_id):

    cuser = get_current_c_user(request)

    if request.method == "GET":
        u = get_object_or_404(Articles,id=type_id)
        all_article = session_mixs.get(request,"ars")

        if not all_article: 
            all_article = Articles.objects.count()
            session_mixs.set(request,ars=all_article)

        title = u.title
        content = u.content 
        tags =[ tag.content for tag in  get_list_or_404(ATags,article=u)]
        file_path = u.attach_file.url
        if_exist_next = False
        # if_right = cuser.if_right_article(u.id)
        id  = u.id
        if_ahead = False
        if all_article > u.id:
            if_exist_next = u.id +1 
        
        if u.id != 1:
            if_ahead = u.id -1


        context  = RequestContext(request,{
                'title':title,
                'id':id,
                'content':content,
                'tags':tags,
                'file_path':file_path,
                'if_exist_next':if_exist_next,
                'if_ahead':if_ahead,
                'if_right':None,
                'user_name':cuser,
                'link':u.link,
                'u':cuser,
            })
        return HttpResponse(template.render(context))
